package erwiki.part.datapersistence.json;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Date;

import org.eclipse.core.runtime.IPath;
import org.elwiki_data.AttachmentContent;
import org.elwiki_data.PageAclEntry;
import org.elwiki_data.PageAttachment;
import org.elwiki_data.PageContent;
import org.elwiki_data.PageReference;
import org.elwiki_data.PagesStore;
import org.elwiki_data.WikiPage;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import erwiki.api.IStorageCdo;
import erwiki.api.core.Engine;
import erwiki.part.datapersistence.internal.PluginActivator;
import erwiki.part.datapersistence.json.converters.AttachmentContentConverter;
import erwiki.part.datapersistence.json.converters.DateConverter;
import erwiki.part.datapersistence.json.converters.PageAclEntryConverter;
import erwiki.part.datapersistence.json.converters.PageAttachmentConverter;
import erwiki.part.datapersistence.json.converters.PageContentConverter;
import erwiki.part.datapersistence.json.converters.PageReferenceConverter;
import erwiki.part.datapersistence.json.converters.PagesStoreConverter;
import erwiki.part.datapersistence.json.converters.WikiPageConverter;

public class JsonSerialiser {

	private IPath workPath;

	public JsonSerialiser(Engine engine) {
		this.workPath = engine.getWorkDir();
	}

	public void SaveData() throws IOException {
		// Gson gson = new GsonBuilder().enableComplexMapKeySerialization().setPrettyPrinting().create();
		Gson gson = new GsonBuilder()
				.setPrettyPrinting() //@formatter:off
				//.setVersion(1.0)
				.registerTypeAdapter(PagesStore.class, new PagesStoreConverter())
				.registerTypeAdapter(WikiPage.class, new WikiPageConverter())
				.registerTypeAdapter(PageReference.class, new PageReferenceConverter())
				.registerTypeAdapter(PageContent.class, new PageContentConverter())
				.registerTypeAdapter(PageAttachment.class, new PageAttachmentConverter())
				.registerTypeAdapter(AttachmentContent.class, new AttachmentContentConverter())
				.registerTypeAdapter(PageAclEntry.class, new PageAclEntryConverter())
				.registerTypeAdapter(Date.class, new DateConverter())
				.create(); //@formatter:on

		IStorageCdo storageCdo = PluginActivator.getDefault().getService(IStorageCdo.class);
		PagesStore pagesStore = storageCdo.getPagesStore();
		// EList<WikiPage> pages = pagesStore.getWikipages();

		try (Writer writer = new FileWriter(workPath.append(PersistConstants.FILE_NAME).toFile())) {
			gson.toJson(pagesStore, PagesStore.class, writer);
			writer.close();
		}
	}
}
